package com.yanwq.sayhi.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yanwq.sayhi.exception.ExResponse;
import com.yanwq.sayhi.service.OSSService;
import com.yanwq.sayhi.tool.PathTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：yanweiqiang。
 * 日期：2016/4/21 0021。
 */
@RestController
@RequestMapping(path = "/oss")
public class OSSRest {

    @Autowired
    private OSSService service;
    private ObjectMapper mapper = new ObjectMapper();

    @RequestMapping(path = "/picture", method = RequestMethod.POST)
    public String uploadPicture(@RequestParam MultipartFile mf) {

        File file = new File(PathTool.getRootPath() + "/SayHi/photos/" + mf.getOriginalFilename());

        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new ExResponse(10900, "无法创建图片目录");
            }
        }

        if (file.exists()) {
            if (!file.delete()) {
                throw new ExResponse(10901, "无法删除旧的图片");
            }
        }

        try {
            mf.transferTo(file);

            String[] picUrls = service.uploadPictureBatch(file);
            Map<String, String> urlMap = new HashMap<>();
            urlMap.put("picThumbUrl", picUrls[0]);
            urlMap.put("picMediumUrl", picUrls[1]);
            urlMap.put("picOriginUrl", picUrls[2]);
            return mapper.writeValueAsString(urlMap);
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new ExResponse(10902, "上传图片失败");
    }

    @RequestMapping(path = "/file", method = RequestMethod.POST)
    public String uploadFile(@RequestParam MultipartFile mf) {

        File file = new File(PathTool.getRootPath() + "/SayHi/photos/" + mf.getOriginalFilename());

        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new ExResponse(10900, "无法创建文件目录");
            }
        }

        if (file.exists()) {
            if (!file.delete()) {
                throw new ExResponse(10901, "无法删除旧的文件");
            }
        }

        try {
            mf.transferTo(file);

            String fileUrl = service.uploadFile(file);
            Map<String, String> urlMap = new HashMap<>();
            urlMap.put("fileUrl", fileUrl);
            return mapper.writeValueAsString(urlMap);
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new ExResponse(10902, "上传文件失败");
    }
}
